//
//  ModifyUserInfoVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/5/26.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import HXPhotoPicker

class ModifyUserInfoVC: BaseTabVC {

//    1区
    @IBOutlet weak var userHeaderImageView: UIImageView!
//    2区
    @IBOutlet weak var userNameTF: UITextField!
    @IBOutlet weak var sexLabel: UILabel!
    @IBOutlet weak var birthdayLabel: UILabel!
//    3区
    @IBOutlet weak var mobileTF: UITextField!
    @IBOutlet weak var emailLabel: UITextField!
//    签名
    @IBOutlet weak var signTV: IQTextView!
    
    private var rightItem: UIBarButtonItem!
    
    private let viewModel = ModifyUserInfoViewModel()
    
    var user: User? {
        
        didSet {
            
            if let user = user {
                
                viewModel.user = user
            }
        }
    }
    
    
    /// 0 为我的，1为其它用户，不可编辑
    var pageType: Int = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupData()
    }
    
    func setupUI() {
        
        if pageType == 1 {
            
            userNameTF.isEnabled = false
            signTV.isEditable = false
        } else {
            
            rightItem = UIBarButtonItem.init(title: "提交", style: .plain, target: self, action: #selector(commit))
            
            self.navigationItem.rightBarButtonItem = rightItem
        }
        
        self.userHeaderImageView.setImage(string: self.viewModel.user?.logo_new?.getQiniuThumb(thumbImageWidth), placeholder: #imageLiteral(resourceName: "default"))
        
        self.userHeaderImageView.isUserInteractionEnabled = true
        self.userHeaderImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showBigHeadImageView)))
        
    }
    
    func setupData() {
        
        if pageType == 0 {
            
            self.title = "修改用户信息";
        }
        
        userNameTF.text = viewModel.user?.nickname
        emailLabel.text = viewModel.user?.email
        mobileTF.placeholder = viewModel.user?.mobile
        
        signTV.text = viewModel.user?.label
        
        userNameTF.rx.text.orEmpty.bind(to: viewModel.nickname).disposed(by: disposeBag)
        emailLabel.rx.text.orEmpty.bind(to: viewModel.email).disposed(by: disposeBag)
        signTV.rx.text.orEmpty.bind(to: viewModel.sign).disposed(by: disposeBag)
        
        viewModel.sex.asObservable().bind(to: sexLabel.rx.sex).disposed(by: disposeBag)
        viewModel.birthday.asObservable().bind(to: birthdayLabel.rx.birthday).disposed(by: disposeBag)

        if pageType == 0 {
            viewModel.userHasChanged.bind(to: rightItem.rx.isEnabled).disposed(by: disposeBag)
        }
        
        
        self.viewModel.message.asObservable().bind(to: self.view.rx.showToast).disposed(by: disposeBag)
        self.viewModel.showLoading.asObservable().bind(to: self.view.rx.showToastActivity).disposed(by: disposeBag)
        self.viewModel.loadSuccess = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    @objc func commit() {
        
        self.viewModel.commit()
    }
    
    @objc func showBigHeadImageView() {
        
        var photo:SKPhoto!
        
        if let url = viewModel.user?.logo_new {
        
            photo = SKPhoto.photoWithImageURL(url, holder: userHeaderImageView.image)
        } else {
            
            photo = SKPhoto.photoWithImage(userHeaderImageView.image!)
        }
    
        SKPhotoBrowserOptions.displayAction = true
        SKPhotoBrowserOptions.displayStatusbar = true
        SKPhotoBrowserOptions.displayCounterLabel = true
        SKPhotoBrowserOptions.displayBackAndForwardButton = true
        SKPhotoBrowserOptions.enableSingleTapDismiss = true
        
        let browser = SKPhotoBrowser(photos: [photo], initialPageIndex: 0)
        browser.cancelTitle = "取消"
        browser.delegate = self
        browser.statusBarStyle = .lightContent
        
        self.present(browser, animated: true, completion: nil)
        
    }
}

extension ModifyUserInfoVC: SKPhotoBrowserDelegate {
    
    func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? {
        
        return self.userHeaderImageView
    }
}

extension ModifyUserInfoVC {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if pageType == 1 {
            return
        }
        
        let section = indexPath.section
        let row = indexPath.row
        
        if section == 0 && row == 0 {// 头像
            
            self.changeHeadImage()
            return
        }
        
        if section == 1 && row == 1 {// 性别
            
            self.changeSex()
            
            return
        }
        
        if section == 1 && row == 2 {// 生日
            
            self.changeBirthday()
            return
        }
        
        if section == 2 && row == 0 {// 手机号
            
            self.viewModel.message.value = "抱歉，暂时不支持手机号修改"
            return
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 1 {
            
            if pageType == 1 {
                
                return 2
            }
            
            return 3
        }
        
        if section == 2 {
            
            if pageType == 1 {
                
                return 0
            }
            
            return 2
        }
        
        return 1
    }
    
    func changeHeadImage() {
        
        let broswer = HXPhotoManager(type: .photo)
        
        broswer?.configuration.maxNum = 1
        broswer?.configuration.singleSelected = true
        broswer?.configuration.singleJumpEdit = true
        
        broswer?.configuration.openCamera = true
        broswer?.configuration.lookGifPhoto = true
        broswer?.configuration.lookLivePhoto = false
        
        broswer?.configuration.movableCropBoxEditSize = true
        broswer?.configuration.movableCropBox = true
        broswer?.configuration.movableCropBoxCustomRatio = CGPoint(x: 1, y: 1)
        broswer?.configuration.navBarBackgroudColor = UIColor.black
        
        self.hx_presentAlbumListViewController(with: broswer, done: {
            
            [weak self] allList, photoList, videoList, imageList, original, viewController in
            guard let `self` = self else { return }
            
            guard let model = allList?.first else { return }
            
            self.uploadHeadImage(model: model)
            
        }, cancel: nil)
        
    }
    
    func uploadHeadImage(model:HXPhotoModel) {
        
        self.userHeaderImageView.image = model.thumbPhoto
        
        NetAPI.uploadToQN([model]) {
            
            [weak self] isVideo, keys, errmsg, size in
            guard let `self` = self else { return }
            
            if let msg = errmsg {
                
                self.showToast(msg)
                
                return
            }
            
            NetAPI.changeprofile(params: ["logo":(keys?.first)!]).request(completion: {
                
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                if let msg = errmsg {
                    
                    self.showToast(msg)
                    
                    return
                }
                
                self.showToast("修改成功")
                
//                [[NSNotificationCenter defaultCenter]postNotificationName:kChangUserInfoNotifationKey object:nil];
                
                NotificationCenter.default.post(name: kReloadUserNotifationName, object: nil, userInfo: nil)
                
            })
        }
    }
    
    func changeSex() {
        
        let alertVC = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        alertVC.addAction(UIAlertAction.init(title: "男", style: .default, handler: {
            
            [weak self] _ in
            guard let `self` = self else { return }
            
            self.viewModel.sex.value = .Man
        }))
        
        alertVC.addAction(UIAlertAction.init(title: "女", style: .default, handler: {
            
            [weak self] _ in
            guard let `self` = self else { return }
            
            self.viewModel.sex.value = .Woman
        }))
        
        alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func changeBirthday() {
        
        let dateVC = SelectDateVC()
        
        dateVC.delegate = self
        dateVC.selectDate = self.viewModel.birthday.value
        
        dateVC.showView(self)
        
    }
}

extension ModifyUserInfoVC: SelectDateVCDelegate {
    
    func didSelect(_ date: Date) {
        
        self.viewModel.birthday.value = date
    }
}
